<?php

namespace common\response;

use  Yii;
use yii\helpers\Url;

class Response
{
    public $errorRoute = '';

    function susess($data = [], $msg = '')
    {
        self::response(true, $msg, $data);
    }

    function json($data)
    {
        echo is_array($data) ? json_encode($data) : $data;
        exit;
    }

    function error($msg = '', $data = [], $json = true)
    {
        $errorTipType = \Cm::$req->isPost() ? "json" : "html";
        if ($errorTipType == "json"||empty($this->errorRoute))
            self::response(false, $msg, $data);
        else
            $this->redirect($this->errorRoute, "?tip={$msg}");
    }

    function paging($data, $msg = '')
    {
        $data['code'] = !count($data['data']) ? -1 : (empty($msg) ? 0 : -1);
        $data['msg'] = !count($data['data']) ? '暂无相关数据' : $msg;
        echo json_encode($data);
        exit;
    }

    function render($context, $view, $data = [], $title = '', $params = [])
    {
        if (!empty($title))
            $context->getView()->title = $title;

        $context->getView()->params['map'] = isset($data['map']) ? $data['map'] : [];
        $context->getView()->params['is_heide'] = !isset($data['is_heide']) ? 0: 1;
//        $size = memory_get_usage()-M_START;
//        $unit = array('b','kb','mb','gb','tb','pb');
//        $size = @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
//        echo $size;

        return $context->render($view, $data);
    }

    function redirect($route, $param = '')
    {
        $res = Yii::$app->getResponse()->redirect(Url::to($route) . $param, 302);
        $res->send();
        exit;
        //$context->redirect($route)->send();
    }

    private static function response($status, $msg, $data)
    {

        $res = ['flag' => $status, 'code' => $status ? 0 : -1, 'msg' => $msg, 'data' => $data];
        echo json_encode($res);
        exit;
    }
}